<template>
  <div>
    <el-breadcrumb separator-class='el-icon-arrow-right'>
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class='box-card'>
      <el-row>
        <el-col>
          <el-button type='primary' @click='addDialogVisible = true'>添加角色</el-button>
        </el-col>
      </el-row>

      <el-table :data='rolesList' border stripe>
        <el-table-column type='expand'>
          <template slot-scope='scope'>
            <el-row :class="['bdtop', i1 === 0 ? 'bdbottom' : '', 'vcenter']" v-for='(item1,i1) in scope.row.children'
                    :key='item1.id'>
              <el-col :span='5'>
                <el-tag closable @close='removeRightById(scope.row,item1.id)'>{{ item1.authName }}</el-tag>
                <i class='el-icon-caret-right'></i>
              </el-col>
              <el-col :span='19'>
                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']" v-for='(item2,i2) in item1.children'
                        :key='item2.id'>
                  <el-col :span='6'>
                    <el-tag type='success' closable @close='removeRightById(scope.row,item2.id)'>{{
                        item2.authName
                      }}
                    </el-tag>
                    <i class='el-icon-caret-right'></i>
                  </el-col>
                  <el-col :span='18'>
                    <template>
                      <el-tag v-for='(item3) in item2.children' :key='item3.id' type='warning' closable
                              @close='removeRightById(scope.row,item3.id)'>{{ item3.authName }}
                      </el-tag>
                    </template>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type='index' label='序号'></el-table-column>
        <el-table-column prop='roleName' label='角色名称'></el-table-column>
        <el-table-column prop='roleDesc' label='角色描述'></el-table-column>
        <el-table-column label='操作'>
          <template v-slot='scope'>
            <el-button size='mini' type='primary' icon='el-icon-edit' @click='showEditDialog(scope.row.id)'>编辑
            </el-button>
            <el-button size='mini' type='danger' @click='rolesdelete(scope.row.id)' icon='el-icon-delete'>删除</el-button>
            <el-button size='mini' @click='showSetRightDialog(scope.row)' type='warning' icon='el-icon-search'>分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的对话框 -->
    <el-dialog title='分配权限' :visible.sync='SetRightDialogVisible' width='50%' @close='SetRightDialogVisibleClosed'>
      <!-- 树形控件 -->
      <el-tree :data='rightsList' :props='treeProps' show-checkbox node-key='id' :default-expand-all='true'
               :default-checked-keys='defKeys' ref='treeRef'></el-tree>
      <span slot='footer' class='dialog-footer'>
        <el-button @click='SetRightDialogVisible = false'>取 消</el-button>
        <el-button type='primary' @click='allotRights'>确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色对话框 -->
    <el-dialog title='添加角色' :visible.sync='addDialogVisible' @close='addDislogClosed'>
      <el-form :model='addRolesForm' ref='addRolesFormRef' label-width='100px'>
        <el-form-item label='角色名称' prop='roleName'>
          <el-input v-model='addRolesForm.roleName'></el-input>
        </el-form-item>
        <el-form-item label='角色描述' prop='roleDesc'>
          <el-input v-model='addRolesForm.roleDesc'></el-input>
        </el-form-item>
      </el-form>
      <span slot='footer' class='dialog-footer'>
        <el-button @click='addDialogVisible = false'>取 消</el-button>
        <el-button type='primary' @click='addRolesUser'>确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog title='修改角色' :visible.sync='editDialogVisible' width='30%'>
      <el-form :model='editRolesForm' ref='editFormRef' label-width='100px'>
        <el-form-item label='角色名称' prop='roleName'>
          <el-input v-model='editRolesForm.roleName'></el-input>
        </el-form-item>
        <el-form-item label='角色描述' prop='roleDesc'>
          <el-input v-model='editRolesForm.roleDesc'></el-input>
        </el-form-item>
      </el-form>
      <span slot='footer' class='dialog-footer'>
        <el-button @click='editDialogVisible = false'>取 消</el-button>
        <el-button type='primary' @click='editFormInfo'>确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      SetRightDialogVisible: false,
      rightsList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 树形控件 -> 默认选中的节点id值数组
      defKeys: [],
      rolesId: '',
      editDialogVisible: false,
      editRolesForm:
        {
          roleName: '',
          roleDesc: ''
        },
      addDialogVisible: false,
      addRolesForm:
        {
          roleName: '',
          roleDesc: ''
        }
    }
  },

  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败!')
      }
      this.rolesList = res.data
      //  console.log(this.rolesList)
    },

    async removeRightById(roles, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除!')
      }
      const { data: res } = await this.$http.delete(`roles/${roles.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败!')
      }
      roles.children = res.data
    },

    async showSetRightDialog(roles) {
      this.rolesId = roles.id
      this.SetRightDialogVisible = true
      // 获取所有权限列表
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败!')
      }

      this.rightsList = res.data
      //   console.log(res.data)
      // 递归获取三级节点
      this.getLeafKeys(roles, this.defKeys)
      this.SetRightDialogVisible = true
    },

    SetRightDialogVisibleClosed() {
      // 清空 defkeys 数组  避免累积
      this.defKeys = []
    },

    getLeafKeys(node, arr) {
      // 如果当前node没有children属性则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },

    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(), //...代表的是值，没有的话代表的是数组对象
        ...this.$refs.treeRef.getHalfCheckedKeys() //...代表的是值，没有的话代表的是数组对象
      ]

      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.rolesId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败!')
      }
      this.$message.success('分配权限成功!')
      this.SetRightDialogVisible = false
      this.SetRightDialogVisibleClosed()
      this.getRolesList()
    },

    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色失败!')
      }
      this.editRolesForm = res.data
    },

    editFormInfo() {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) return
        this.$http
          .put('roles/' + this.editRolesForm.roleId, {
            roleName: this.editRolesForm.roleName,
            roleDesc: this.editRolesForm.roleDesc
          })
          .then(res => {
            if (res.data.meta.status !== 200) {
              return this.$message.error('修改角色失败!')
            }
            this.$message.success('修改角色成功!')
            this.getRolesList()
          })
        this.editDialogVisible = false
      })
    },

   async addRolesUser(){
      const { data: res } = await this.$http.post('roles', this.addRolesForm)
     if (res.meta.status !== 201) {
       return this.$message.error('添加角色失败!')
     }
     this.$message.success('添加角色成功!')
     this.getRolesList()
     this.addDialogVisible = false
    },

    addDislogClosed(){
      this.$refs.addRolesFormRef.resetFields()
    },

    async rolesdelete(id) {
      // 询问用户是否删除用户
      const confirmRusult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '永久删除该角色', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmRusult)
      // 用户点击了删除,则返回字符串 confirm
      // 用户取消了删除,则返回字符串 cancel
      if (confirmRusult !== 'confirm') {
        return this.$message.info('已经取消了删除')
      }
      this.$http.delete('roles/' + id).then(res => {
        const {data: response} = res
        console.log(response)
        if (response.meta.status !== 200) {
          return this.$message.error('该角色删除失败')
        }
        this.$message.success('该角色已经删除')
        this.getRolesList()
      })
    }
  }
}
</script>

<style lang='less' scoped>
.el-table {
  margin-top: 15px;
}

.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>

